package com.chen.serviceprice.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.internalcommon.constant.CommonStatusEnum;
import com.chen.internalcommon.dto.PriceRule;
import com.chen.internalcommon.dto.ResponseResult;
import com.chen.serviceprice.mapper.PriceRuleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author chenLiuPing
 **/
@Service
@Slf4j
public class PriceRuleService {

    @Autowired
    private PriceRuleMapper priceRuleMapper;

    /**
     * 添加计价规则
     * @param priceRule
     * @return
     */
    public ResponseResult add(PriceRule priceRule) {
        log.info("add start");
        // 设置fareType fareVersion
        String cityCode = priceRule.getCityCode();
        String vehicleType = priceRule.getVehicleType();
        String fareType = cityCode + "$" + vehicleType;
        // 查询计价规则是否存在
        LambdaQueryWrapper<PriceRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PriceRule::getFareType, fareType);
        List<PriceRule> selectList = priceRuleMapper.selectList(queryWrapper);
        if (selectList.size() > 0) {
            log.info("添加失败，计价规则已存在");
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_EXISTS);
        }
        priceRule.setFareType(fareType);
        priceRule.setFareVersion(1);
        try {
            priceRuleMapper.insert(priceRule);
        } catch (Exception e) {
            log.info("插入异常, 添加失败");
            e.printStackTrace();
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_EXISTS);
        }
        log.info("priceRule添加成功");
        return ResponseResult.success();
    }

    /**
     * 修改计价规则
     */
    public ResponseResult edit(PriceRule priceRule) {
        // 设置fareType fareVersion
        String cityCode = priceRule.getCityCode();
        String vehicleType = priceRule.getVehicleType();
        String fareType = cityCode + "$" + vehicleType;

        // 按照fareVersion排序获取fareType相同的计价规则
        LambdaQueryWrapper<PriceRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PriceRule::getFareType, fareType)
                .orderByDesc(PriceRule::getFareVersion);
        List<PriceRule> selectList = priceRuleMapper.selectList(queryWrapper);
        int fareVersion = 0;
        if (selectList.size() > 0) {
            // 获取fareVersion最大的
            PriceRule selectOne = selectList.get(0);
           // 判断相关的计价规则是否发生变化
            if (Objects.equals(selectOne.getStartFare(), priceRule.getStartFare()) &&
                Objects.equals(selectOne.getStartMile(), priceRule.getStartMile()) &&
                Objects.equals(selectOne.getUnitPricePerMile(), priceRule.getUnitPricePerMile()) &&
                    Objects.equals(selectOne.getUnitPricePerMinute(), priceRule.getUnitPricePerMinute())
            ) {
                log.info("计价规则没有发生变化，修改失败");
                return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_NOT_EDIT);
            }
            fareVersion = selectOne.getFareVersion();
        }
        // TODO 按照正常逻辑 这里没有查到对应的计价规则时就不允许更改 而不是直接插入
        priceRule.setFareVersion(++fareVersion);
        priceRule.setFareType(fareType);
        try {
            priceRuleMapper.insert(priceRule);
            log.info("计价规则修改成功");
        } catch (Exception e) {
            log.info("插入异常，计价规则修改事变");
            e.printStackTrace();
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_EXISTS);
        }
       return ResponseResult.success();
    }

    /**
     * 判断计价规则是否最新
     */
    public ResponseResult isNew(String fareType, Integer fareVersion) {
        log.info("isNew start");
        PriceRule newestPriceRule = getNewestPriceRule(fareType);
        if (newestPriceRule == null) {
            log.info("fareType：{}==》计价规则不存在", fareType);
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_EMPTY);
        }
        Integer newestFareVersion = newestPriceRule.getFareVersion();
        if (newestFareVersion > fareVersion) {
            return ResponseResult.success(false);
        }
        // newestFareVersion < fareVersion 时  应该是个错误的 而不是直接返回true
        return ResponseResult.success(true);
    }

    /**
     * 查询最新的计价规则
     */
    public ResponseResult getNewestVersion(String fareType) {
        log.info("getNewestVersion start");
        PriceRule newestPriceRule = getNewestPriceRule(fareType);
        if (newestPriceRule == null) {
            log.info("fareType：{}==》计价规则不存在", fareType);
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_EMPTY);
        }
        return ResponseResult.success(newestPriceRule);
    }
    private PriceRule getNewestPriceRule(String fareType) {
        LambdaQueryWrapper<PriceRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PriceRule::getFareType, fareType)
                .orderByDesc(PriceRule::getFareVersion);
        List<PriceRule> priceRules = priceRuleMapper.selectList(queryWrapper);
        if (priceRules.size() == 0) {
            return null;
        }
        return priceRules.get(0);
    }

    /**
     * 根据城市编码和车型查询对应计价规则是否存在
     * @param cityCode
     * @param vehicleType
     * @return
     */
    public ResponseResult ifExists(String cityCode, String vehicleType) {
        LambdaQueryWrapper<PriceRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PriceRule::getCityCode, cityCode)
                .eq(PriceRule::getVehicleType, vehicleType)
                .orderByDesc(PriceRule::getFareVersion);
        List<PriceRule> priceRules = priceRuleMapper.selectList(queryWrapper);
        if (priceRules.size() > 0) {
            log.info("cityCode:{}, vehicleType:{},对应计价规则存在", cityCode, vehicleType);
            return ResponseResult.success(true);
        }
        log.info("cityCode:{}, vehicleType:{},对应计价规则不存在", cityCode, vehicleType);
        return ResponseResult.success(false);
    }
}
